package hibernate;

import java.util.Iterator;
import java.util.List;

import modelo.Curso;
import modelo.HorasMateria;
import modelo.Materia;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class HibernateDaoCurso {
	private static HibernateDaoCurso instancia;
	private static SessionFactory sf;
	
	public static HibernateDaoCurso getInstancia(){
		if(instancia == null) {
			instancia = new HibernateDaoCurso();
			sf = HibernateUtil.getSessionFactory();
			
		}
		return instancia;
	}
	public void actualizarCurso(String ncurso,String nmateria,int cantidad){
		Session session = sf.openSession();
		session.beginTransaction();
		Curso c = HibernateDaoCurso.getInstancia().buscarCurso(ncurso);
		Materia m = HibernateDaoMateria.getInstancia().buscarMateriaPorNombre(nmateria);
		HorasMateria hm= new HorasMateria(1,m ,cantidad);
		c.agregarHorasMaterias(hm);
		session.update(c);
		session.getTransaction().commit();
		session.close();
	}
	
	public void grabarCurso(Curso c){
		Session session = sf.openSession();
		session.beginTransaction();
		session.save(c);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}
	
	public Curso buscarCurso(int id){
		Session session =  sf.openSession();
		Curso c = (Curso) session.createQuery("From Curso c where c.Id_Curso = (:id)").setParameter("id", id).uniqueResult();
		session.close();
		return c;
	}
	
	public Curso buscarCurso(String nom){
		Session session =  sf.openSession();
		int i= (int) session.createQuery("select c.Id_Curso from Curso c where c.nombre_Curso =(:nom)").setParameter("nom", nom).uniqueResult();
		Curso c = buscarCurso(i);
		session.close();
		return c;
	}
	
	public List<Curso> traerCursos()
	{
		Session session = sf.openSession();
		@SuppressWarnings("unchecked")
		List<Curso> c =  session.createQuery("From Curso").list();
		return c;
		
	}
	
	public void eliminarCurso(int id){
		Session session =  sf.openSession();
		session.beginTransaction();
		Curso c = buscarCurso(id);
		session.delete(c);
		session.getTransaction().commit();
		session.close();
		
		
	}
	
	public String[] traerCursosParaCombo(){
		Session session= sf.openSession();
	
		long cant = (long) session.createQuery("select count(*) from Curso").uniqueResult();
		
		@SuppressWarnings("rawtypes")
		Iterator i = session.createQuery("select c.nombre_Curso From Curso c").iterate();
		
		String cur[] = new String[(int) cant];
		int j=0;
		while(i.hasNext())
		{
			String tupla = (String) i.next();
			cur[j]= (String) tupla;
			j++;
		}
		session.close();
		return cur;
		
	}
}
